#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

int counter=0;
pthread_mutex_t mutex;

void* thread_func(void* arg){
    for(int i=0;i<100000;i++){
        pthread_mutex_lock(&mutex);
        counter++;
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(NULL);
}

int main(){
    int num_threads=5;
    pthread_t threads[num_threads];
    int rc;
    //初始化互斥锁
    pthread_mutex_init(&mutex, NULL);
    for(int i=0;i<num_threads;i++){
        rc=pthread_create(&threads[i], NULL, thread_func, NULL);
        if(rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }
    for(int i=0;i<num_threads;i++){
        pthread_join(threads[i], NULL);
    }
    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    printf("counter的值为:%d\n", counter);
    pthread_exit(NULL);
    return 0;
}